package com.simon.hse.activity.risk;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.DropDownOutput;
import com.simon.hse.http.entity.OperationAndWorkListOutput;
import com.simon.hse.http.entity.RiskActivityInput;
import com.simon.hse.interfaces.PopListener;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * 操作程序
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_risk_function2)
public class RiskOperationActivity extends BaseActivity implements PopListener {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.ll_risk_level)
    LinearLayout mLl_risk_level;

    @ViewInject(R.id.tv_risk_level)
    TextView mTv_risk_level;

    @ViewInject(R.id.et_job_step)
    EditText mEt_job_step;

    @ViewInject(R.id.et_job_task)
    EditText mEt_job_task;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;

    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private List<OperationAndWorkListOutput.DataBean.PageDataBean> mDataBeanList = new ArrayList<>();// 操作程序列表
    private String levelId;// 风险级别id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("操作程序");

        initRecyclerView();
        initData();
    }

    @Event(value = {R.id.iv_common_left, R.id.ll_risk_level})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.ll_risk_level:
                initRiskLevelPop();
                break;
        }
    }

    private void initRecyclerView() {
        mEt_job_step.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mDataBeanList.clear();
                initData();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mEt_job_task.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                mDataBeanList.clear();
                initData();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage * 10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(RiskOperationActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(RiskOperationActivity.this, R.layout.layout_item_rist_function1, mDataBeanList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<OperationAndWorkListOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, OperationAndWorkListOutput.DataBean.PageDataBean dataBean) {
                TextView tv_risk_title = holder.getView(R.id.tv_risk_title);
                TextView tv_risk_level = holder.getView(R.id.tv_risk_level);
                TextView tv_risk_task = holder.getView(R.id.tv_risk_task);

                tv_risk_title.setText(dataBean.getJobSteps());
                tv_risk_task.setText(dataBean.getJobItem());
                String riskLevelText = dataBean.getRiskLevelText().toString();
                tv_risk_level.setText(riskLevelText);
                switch (riskLevelText) {
                    case "二级":
                        tv_risk_level.setBackgroundResource(R.drawable.rect_yellow_corner_5);
                        break;
                    case "三级":
                        tv_risk_level.setBackgroundResource(R.drawable.rect_red_corner_5);
                        break;
                }
            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {
                Intent intent = new Intent(RiskOperationActivity.this, RiskOperationDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("ID", mDataBeanList.get(position).getId());
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mCommonEmptyAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    /**
     * 操作程序-列表
     */
    private void initData() {
        RiskActivityInput riskActivityInput = new RiskActivityInput();
        RiskActivityInput.ModelBean modelBean = new RiskActivityInput.ModelBean();
        if (!TextUtils.isEmpty(levelId)) {
            modelBean.setRiskLevel(levelId);
        }
        String step = mEt_job_step.getText().toString();
        if (!TextUtils.isEmpty(step)) {
            modelBean.setJobSteps(step);
        }
        String task = mEt_job_task.getText().toString();
        if (!TextUtils.isEmpty(task)) {
            modelBean.setJobTask(task);
        }

        riskActivityInput.setModel(modelBean);
        riskActivityInput.setLimit(10);
        riskActivityInput.setOffset(10 * (currentPage - 1));

        Call<String> call = HttpManager.getInstance().requestService().OPERATION_LIST(HttpManager.getInstance().requestBody(riskActivityInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                OperationAndWorkListOutput operationAndWorkListOutput = new Gson().fromJson(result, OperationAndWorkListOutput.class);
                if (operationAndWorkListOutput.getResult().equals("Success")) {
                    totalPage = operationAndWorkListOutput.getData().getRowCount();
                    List<OperationAndWorkListOutput.DataBean.PageDataBean> pageDataBeanList = operationAndWorkListOutput.getData().getPageData();
                    mDataBeanList.addAll(pageDataBeanList);
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(operationAndWorkListOutput.getMessage().toString());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 风险级别-Pop
     */
    private void initRiskLevelPop() {
        View inflate = LayoutInflater.from(RiskOperationActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(RiskOperationActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(RiskOperationActivity.this, R.layout.layout_item_common_more_department, MyApplication.getInstance().mRiskLevelList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = MyApplication.getInstance().mRiskLevelList.get(position);
                levelId = valueBean.getKey();
                mTv_risk_level.setText(valueBean.getValue());
                mDataBeanList.clear();
                initData();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(RiskOperationActivity.this, inflate, mLl_risk_level);
    }


    @Override
    public void upData() {
        currentPage = 1;
        mDataBeanList.clear();
        initData();
    }
}
